package com.newenergy.wisehome.ui.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.PermissionChecker;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.MyEvent;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.StorageHelper;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.gateway.account.GatewayManageFragment;
import com.newenergy.wisehome.gateway.account.LoginFragment;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.services.BDService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import me.weyye.hipermission.HiPermission;
import me.yokeyword.fragmentation.ISupportFragment;


/**
 * 设置界面.
 */
public class SettingFragment extends BaseFragment {

    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;

    @BindView(R.id.tv_family_info)
    TextView mTvFamilyInfo;
    @BindView(R.id.tv_family_name)
    TextView mTvFamilyName;
    @BindView(R.id.btn_family_into)
    Button mBtnFamilyInto;
    @BindView(R.id.tv_current_family)
    TextView mTvCurrentFamily;
    @BindView(R.id.rl_family_info)
    RelativeLayout mRlFamilyInfo;
    @BindView(R.id.tv_advanced_func)
    TextView mTvAdvancedFunc;
    @BindView(R.id.tv_advanced_name)
    TextView mTvAdvancedName;
    @BindView(R.id.btn_switch)
    Button mBtnSwitch;
    @BindView(R.id.rl_speech)
    RelativeLayout mRlAdvanced;
    @BindView(R.id.tv_langure_name)
    TextView mTvLangureName;
    @BindView(R.id.rl_Langure_info)
    RelativeLayout mRlLangureInfo;
    @BindView(R.id.rl_room_info)
    RelativeLayout mRlRoomInfo;
    @BindView(R.id.rl_device_info)
    RelativeLayout mRlDeviceInfo;
    @BindView(R.id.tv_room_name)
    TextView mTvRoomName;
    @BindView(R.id.tv_device_name)
    TextView mTvDeviceName;
    @BindView(R.id.btn_room_into)
    ImageView mBtnRoomInto;
    @BindView(R.id.rl_about)
    RelativeLayout rl_about;
    @BindView(R.id.rl_hea_share)
    RelativeLayout rlHeaShare;
    @BindView(R.id.tv_hea_share)
    TextView tvHeaShare;
    @BindView(R.id.rl_handset_share)
    RelativeLayout rlHandsetShare;

    private Family mCurrFamily;
    private int confirType = 0;//此处0代表不跳转，1代表确认的时候跳转到家庭列表，2代表跳转至设置界面


    @Override
    public int getLayoutId() {
        return R.layout.fragment_setting;
    }


    public static ISupportFragment newInstance() {
        return new SettingFragment();
    }

    @Override
    public void init(View rootView) {
        registerEventBus();
        /*boolean serviceRunning = mainActivity.isServiceRunning();
        Log.e("LFX", "serviceRunning==" + serviceRunning);
        ToastUtil.toast("测试语音服务是否存活=="+serviceRunning);*/
        mTvPage.setText(getString(R.string.setting));
        mCurrFamily = AppManager.getInstance(getContext()).mCurrFamily;
        if (mCurrFamily != null) {
            mTvCurrentFamily.setText(mCurrFamily.getName());
            mTvDeviceName.setTextColor(getResources().getColor(R.color.enable_font));
            mTvRoomName.setTextColor(getResources().getColor(R.color.enable_font));
        } else {
            mTvRoomName.setTextColor(getResources().getColor(R.color.unable_font));
            mTvDeviceName.setTextColor(getResources().getColor(R.color.unable_font));
            mTvCurrentFamily.setText(getString(R.string.no_family));
        }

        mRlLangureInfo.setVisibility(View.GONE);

        if (LocaleUtil.getLanguage().startsWith("zh")) {
            ininLangure();
        } else {
            mTvLangureName.setText(getString(R.string.en_uk));
            mRlAdvanced.setVisibility(View.GONE);
        }

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mCurrFamily = AppManager.getInstance(getContext()).mCurrFamily;
            if (mCurrFamily != null) {
                mTvCurrentFamily.setText(mCurrFamily.getName());
                mTvDeviceName.setTextColor(getResources().getColor(R.color.enable_font));
                mTvRoomName.setTextColor(getResources().getColor(R.color.enable_font));
            } else {
                mTvRoomName.setTextColor(getResources().getColor(R.color.unable_font));
                mTvDeviceName.setTextColor(getResources().getColor(R.color.unable_font));
                mTvCurrentFamily.setText(getString(R.string.no_family));
            }
        }
    }


    private void ininLangure() {
        int status = SPUtil.getInteger(Constants.STATUS_LANGURE, Constants.STATUS_CHINESE);
        //普通话 = "cmn-Hans-CN" ， 粤语 = "yue-Hans-CN" ，  四川话 = "sichuan-Hans-CN" ， 英语 = "en-GB" ;
        String language = StorageHelper.getLanguage();
        switch (language) {
            case "cmn-Hans-CN":
                mTvLangureName.setText(getString(R.string.mandarin));
                break;
            case "yue-Hans-CN":
                mTvLangureName.setText(getString(R.string.cantonese));
                break;
            case "sichuan-Hans-CN":
                mTvLangureName.setText(getString(R.string.sichuan));
                break;
            /*case "en-GB":
                mTvLangureName.setText(getString(R.string.en_uk));
                break;*/
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        boolean b = checkMike();
        mBtnSwitch.setSelected(b);
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_family_into,
            R.id.btn_switch, R.id.btn_lighting_share, R.id.rl_family_info,
            R.id.rl_lighting_share, R.id.rl_Langure_info, R.id.rl_room_info,
            R.id.rl_device_info, R.id.rl_about, R.id.rl_hea_share, R.id.tv_hea_share,
            R.id.rl_handset_share, R.id.btn_hea_share, R.id.btn_handset_share,
            R.id.rl_gateway
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;

            case R.id.tv_back:
                doBack();
                break;

            case R.id.btn_family_into:
                start(FramliyFragment.newInstance());

                break;

            case R.id.rl_family_info:

                start(FramliyFragment.newInstance());
                break;

            case R.id.btn_lighting_share:
                start(SelectFamilyFragment.newInstance("group_share"));

                break;

            case R.id.rl_lighting_share:
                start(SelectFamilyFragment.newInstance("group_share"));

                break;

            case R.id.rl_hea_share:
                start(SelectFamilyFragment.newInstance("hea_share"));
                break;


            case R.id.btn_hea_share:
                start(SelectFamilyFragment.newInstance("hea_share"));

                break;

            case R.id.btn_switch:
                setSwitchStatus();
                break;

            case R.id.rl_Langure_info:
                if (LocaleUtil.getLanguage().startsWith("zh")) {
                    initDialog();
                } else {


                }

                break;

            case R.id.rl_room_info:
                if (mCurrFamily != null) {

                    start(GroupListFragment.newInstace(mCurrFamily));

                } else {
                    confirType = 1;
                    showConfirmDialog(getString(R.string.tip_please_add_family));
                }
                break;

            case R.id.rl_device_info:
                /*if (mCurrFamily != null) {
                    if (mCurrFamily.getType() == 0) {
                        showConfirmDialog(getString(R.string.shared_can_no_operate));

                    } else if (mCurrFamily.getType() == 1) {
                        start(DeviceFragment.newInstace(mCurrFamily));
                    }
                } else {
                    confirType = 1;
                    showConfirmDialog(getString(R.string.tip_please_add_family));
                }*/
                if (mCurrFamily != null) {

                    start(HEAFragment.newInstace(mCurrFamily));

                } else {
                    confirType = 1;
                    showConfirmDialog(getString(R.string.tip_please_add_family));
                }


                break;

            case R.id.rl_about:
                start(AboutUsFragment.newInstace());
                break;


            case R.id.rl_handset_share:
                start(SelectFamilyFragment.newInstance("hea_handset"));
                break;

            case R.id.btn_handset_share:
                start(SelectFamilyFragment.newInstance("hea_handset"));
                break;

            case R.id.rl_gateway:
                showGatewayView();
                break;
        }
    }

    private void showGatewayView() {
//        Boolean isLogin = BaseApp.getmBLUserInfoUnits().checkAccountLogin();
        Boolean isLogin = BLLocalFamilyManager.getInstance().isLogin;
        if (isLogin){
            start(new GatewayManageFragment());
        }else {
            start(new LoginFragment());
        }
    }


    private void setSwitchStatus() {
        boolean b = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            b = HiPermission.checkPermission(mainActivity, Manifest.permission.RECORD_AUDIO);
        } else {
            b = PermissionChecker.checkSelfPermission(mainActivity, Manifest.permission.RECORD_AUDIO) == PermissionChecker.PERMISSION_GRANTED;
        }
        if (b) {
            boolean selected = mBtnSwitch.isSelected();
            selected = !selected;
            if (selected) {
                Intent intent = new Intent(mainActivity, BDService.class);
                intent.putExtra("service_cmd", "startSpeech");
                getContext().startService(intent);
            } else {
                Intent intent = new Intent(mainActivity, BDService.class);
                intent.setAction("stop service");
                mainActivity.stopService(intent);
            }
            mBtnSwitch.setSelected(selected);
            setSpeechEnable(selected);
            EventBus.getDefault().post(new MyEvent(Constants.SPEECH_ENABLE, selected));

            mainActivity.isPermission = false;
        } else {
            confirType = 2;
            showConfirmDialog(getString(R.string.open_recording_permission));
        }
    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setIcon(R.drawable.app);
        builder.setTitle(getString(R.string.select_langure));
        //    指定下拉列表的显示数据
        final String[] cities = {getString(R.string.mandarin), getString(R.string.cantonese), getString(R.string.sichuan)/*, getString(R.string.en_uk)*/};
        //    设置一个下拉的列表选择项
        builder.setItems(cities, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mTvLangureName.setText(cities[which]);
                Toast.makeText(getActivity(), getString(R.string.selection_of_language) + cities[which], Toast.LENGTH_SHORT).show();
                //普通话 = "cmn-Hans-CN" ， 粤语 = "yue-Hans-CN" ，  四川话 = "sichuan-Hans-CN" ， 英语 = "en-GB" ;
                switch (which) {
                    case 0:
                        StorageHelper.setLanguage("cmn-Hans-CN");
                        break;
                    case 1:
                        StorageHelper.setLanguage("yue-Hans-CN");
                        break;
                    case 2:
                        StorageHelper.setLanguage("sichuan-Hans-CN");
                        break;
                    /*case 3:
                        SPUtil.put(Constants.STATUS_LANGURE,Constants.STATUS_ENGLISH);
                        EventBus.getDefault().post(new MyEvent(Constants.STATUS_LANGURE,Constants.STATUS_ENGLISH));
                        break;*/
                }
            }
        });
        builder.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void confirmOperation() {
        if (confirType == 1) {
            start(FramliyFragment.newInstance());
        }

        if (confirType == 2) {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mainActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", mainActivity.getPackageName());
            }
            mainActivity.isPermission = true;
            startActivity(localIntent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(MyEvent event) {
        String tag = event.getTag();
        Object data = event.getData();
        switch (tag) {
            case Constants.SPEECH_ENABLE:
                if ((boolean) data) {
                    mBtnSwitch.setSelected(true);
                } else {
                    mBtnSwitch.setSelected(false);
                }
                break;
        }

    }

}